package demo.practice.stack;

public class P4_2 {

    public static void main(String[] args) {
        P4_2 p4_2 = new P4_2();
        p4_2.findMedianSortedArrays(new int[]{1, 2}, new int[]{3, 4});

    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {


        if (nums1.length == 0 || nums2.length == 0)
            return nums1.length == 0 ? (nums2.length % 2 == 1 ? nums2[nums2.length / 2] : ((double) nums2[nums2.length / 2] + nums2[nums2.length / 2 - 1]) / 2) :
                    (nums1.length % 2 == 1 ? nums1[nums1.length / 2] : ((double) nums1[nums1.length / 2] + nums1[nums1.length / 2 - 1]) / 2)
                    ;


        //首先确定我们需要排序到的位置
        int len1 = nums1.length, len2 = nums2.length;
        //1,2   findex=1  3/2=1
        //2,2   findex=2  4/2=2


        int findex = (len1 + len2) / 2;

        //merge
        int[] m = new int[findex + 1];
        int i = 0, j = 0, k = 0;
        while (i <= findex) {
            m[i++] = j >= len1 ? nums2[k++] : k >= len2 ? nums1[j++] : nums1[j] < nums2[k] ? nums1[j++] : nums2[k++];
        }

        return ((len1 + len2) & 1) == 1 ? m[findex] : ((double) m[findex] + m[findex - 1]) / 2;

    }


}
